<?php

namespace App\Models;

use App\Models\Reservation\Reservation;
use App\Project\Traits\Model\DiabetesDiseaseStage;
use App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;

class Patient extends User
{
    use DiabetesDiseaseStage;

    protected $fillable = [
        'name', 'phone', 'password', 'account', 'nickname', 'age', 'sex', 'birthday', 'diabetes_type',
//        'medical_number',
        'special_illness', 'province', 'city', 'county', 'nation', 'hospital_id', 'doctor_id',
        'cardnumber', 'diabetes_stage'
    ];

    protected static function boot()
    {
        parent::boot();

        //  全局作用域
        static::addGlobalScope('role', function (Builder $builder) {
            $builder->where('tn_user_base.type', 1);
        });

        static::$diabetes_stage_types = config('custom.diabetes_stage.types');
        static::$diabetes_stage_type_keys = config('custom.diabetes_stage.type_keys');
    }

    /**
     * @return mixed
     */
    public function patientsDoctor()
    {
        $record = MedicalRecord::where(['patient_id' => $this->id,'hospital_id'=>$this->hospital_id])->first(['doctor_id']);

        return $record->doctor_id;
    }

    /**
     * 返回某一个医院的某一个医生
     * @return mixed
     */
    public function patientHosiptalsDoctor($patient_id,$hospital_id)
    {
        $record = MedicalRecord::where(['patient_id' => $patient_id,'hospital_id'=>$hospital_id])->first(['doctor_id']);

        return $record->doctor_id;
    }

    /**
     * 患者的病历
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function medicalRecords()
    {
        return $this->hasMany(MedicalRecord::class,'patient_id','id');
    }

    public function records()
    {
        return $this->medicalRecords()
            ->withoutGlobalScope('hasBindDoctor')
            ->orderByDesc('clinic_at')
            ->orderByDesc('id')
            ->get();
    }

    /**
     * 首诊医院
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function hospital()
    {
        return $this->belongsTo(Hospital::class);
    }

    /**
     * @param $size
     * @param $page
     * @param $where
     * @param $type
     * @param $hospital_ids
     * @param $isWear boolean
     * @return \Illuminate\Pagination\LengthAwarePaginator
     */
    public function paging($size, $page, $where, $type, $hospital_ids, $isWear)
    {
        $countQuery = $this->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
            ->where($where)
            ->where([
                ['st_medical_records.doctor_id', '>', 0],
                ['st_medical_records.is_del', '=', 0]
            ]);

        $countQuery->when($isWear, function ($q) {
            return $q->join('tn_sam_wear', 'tn_user_base.id', 'tn_sam_wear.userid');
        });
        $countQuery->when($type == 4, function ($q) use ($hospital_ids) {
            return $q->whereIn('st_medical_records.hospital_id', $hospital_ids);
        });
        $count = $countQuery->distinct()->count('tn_user_base.id');
        //========
        $selectQuery = $this
            ->select(
                [
                    'tn_user_base.id', 'name', 'phone', 'sex', 'age',
//                    'tn_user_base.medical_number',
                    'diabetes_type', 'birthday',
                    'tn_user_base.created_at', 'tn_user_base.updated_at',
                    \DB::raw('max(st_medical_records.clinic_at) as last_clinic_at')
                ])
            ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
            ->where($where)
            ->where([
                ['st_medical_records.doctor_id', '>', 0],
                ['st_medical_records.is_del', '=', 0]
            ])
            ->groupBy('tn_user_base.id')
            ->orderBy('last_clinic_at', 'desc')
            ->orderBy('st_medical_records.created_at', 'desc');

        $selectQuery->when($isWear, function ($q) {
            return $q->join('tn_sam_wear', 'tn_user_base.id', 'tn_sam_wear.userid');
        });
        $selectQuery->when($type == 4, function ($q) use ($hospital_ids) {
            return $q->whereIn('st_medical_records.hospital_id', $hospital_ids);
        });
        $patients = $selectQuery->skip(($page - 1) * $size)->take($size)->get();
        //========


        return new LengthAwarePaginator($patients, $count, $size, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);
    }


    public function pagingAll($where, $type, $hospital_ids, $isWear)
    {
        $countQuery = $this->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
            ->where($where)
            ->where([
                ['st_medical_records.doctor_id', '>', 0],
                ['st_medical_records.is_del', '=', 0]
            ])
            ->whereIn('st_medical_records.hospital_id', $hospital_ids);

        $countQuery->when($isWear, function ($q) {
            return $q->join('tn_sam_wear', 'tn_user_base.id', 'tn_sam_wear.userid');
        });
        if ($type == 4) {
            $countQuery = $countQuery->whereIn('st_medical_records.hospital_id', $hospital_ids);
        }
        $count = $countQuery->distinct()->count('tn_user_base.id');
        //======
        $selectQuery = $this
            ->select(
                [
                    'tn_user_base.id', 'name', 'phone', 'sex', 'age',
//                    'tn_user_base.medical_number',
                    'diabetes_type', 'birthday',
                    'tn_user_base.created_at', 'tn_user_base.updated_at',
                    \DB::raw('max(st_medical_records.clinic_at) as last_clinic_at')
                ])
            ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
            ->where($where)
            ->where([
                ['st_medical_records.doctor_id', '>', 0],
                ['st_medical_records.is_del', '=', 0]
            ])
            ->groupBy('tn_user_base.id')
            ->orderBy('last_clinic_at', 'desc')
            ->orderBy('st_medical_records.created_at', 'desc');

        $selectQuery->when($isWear, function ($q) {
            return $q->join('tn_sam_wear', 'tn_user_base.id', 'tn_sam_wear.userid');
        });
        if ($type == 4) {
            $selectQuery = $selectQuery->whereIn('st_medical_records.hospital_id', $hospital_ids);
        }
        $patients = $selectQuery->get();
        //======


        return new LengthAwarePaginator($patients, $count, 1, 1, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);
    }

    //  预约相关
    public function reservations()
    {
        return $this->belongsToMany(Patient::class, 'reservation')
            ->using(Reservation::class)
            ->withTimestamps();
    }

    //  预约相关

    public function setSpecialIllnessAttribute($value)
    {
        if ('' === $value || is_null($value)) {
            $this->attributes['special_illness'] = '';
        } else {
            $special = app('field')->get('patient.special_illness');

            $this->attributes['special_illness'] = $special[$value];
        }
    }

    public function getSpecialIllnessAttribute($value)
    {
        if ('' === $value || is_null($value)) {
            return ['key' => '', 'value' => ''];
        }

        $special = app('field')->get('patient.special_illness');

        return [
            'key' => array_search($value, $special),
            'value' => $value
        ];
    }

    public function getDiabetesTypeAttribute($value)
    {
        if ($value) {
            $field = app('field')->get('patient');

            return [
                'key' => $value,
                'value' => $field['diabetes_type'][$value]
            ];
        }

        return ['key' => '', 'value' => '未填写'];
    }
}
